package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoMessageEvent;
import com.rw.coco.handler.message.reply.ReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.handler.message.reply.handler.command.sender.RollSender;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;

/**
 * 普通Roll点处理
 * 指令：.r
 */
public class RollHandler implements ReplyHandler {
    private static final int SIMPLE = 0;

    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    public RollHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String command = cocoCommandConfig.commandProp.get(CocoCommandConfig.ROLL);
        String simple = cocoCommandConfig.commandProp.get(CocoCommandConfig.ROLL_SIMPLE);
        this.matcher = CommandMatcher.of(simple, command);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_ROLL);
    }

    @Override
    public boolean trigger(CocoMessageEvent cocoMessageEvent) {
        String message = cocoMessageEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    public void handler(CocoMessageEvent cocoMessageEvent) {
        DiceReply diceReply = cocoMessageEvent.getReplyApi().getDiceReply();
        String message = cocoMessageEvent.getMessage();
        boolean simple = matcher.isMatch(message, SIMPLE);

        // 获取roll点的发送器
        RollSender sender = new RollSender(cocoMessageEvent, matcher.subTrim(message), simple);

        // 如果解析表达式roll点成功，则返回回复
        if (sender.success()) {
            // 获取回复
            String propName = sender.getParser().getName();
            String expression = sender.getExpression();

            String reply = diceReply.roll(cocoMessageEvent, propName, expression);
            cocoMessageEvent.sendBack(reply);
        } else if (sender.getExpressionException() != null) {
            // 表达式解析失败
            cocoMessageEvent.sendBack(diceReply.expressionException(sender.getExpressionException()));
        } else if (sender.getNumberOverflowException() != null) {
            // 数字超大
            cocoMessageEvent.sendBack(diceReply.numberOverflowException(cocoMessageEvent));
        }
    }

    @Override
    public int priority() {
        return matcher.priority();
    }
}
